package camid.distribution.lifecycle.perclient;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import camid.distribution.activeobject.ObjectRegistry;
import camid.distribution.activeobject.ObjectScheduler;

public class LeasingManager {

	private ObjectRegistry registry;
	private Map<String, Lease> leaseMap;
	
	public LeasingManager(ObjectRegistry objectRegistry) 
	{
		this.registry = objectRegistry;
		this.leaseMap = Collections.synchronizedMap(new HashMap<String, Lease> ());
	}

	public ObjectScheduler newLease(ObjectScheduler scheduler, Long lease) 
	{
		String objectId = scheduler.getObjectId();
		leaseMap.put(objectId, new Lease(lease));
		registry.add(scheduler);
		return scheduler;
	}

	public ObjectScheduler getObject(String objectId) 
	{
		ObjectScheduler scheduler = null;
		Lease lease = leaseMap.get(objectId);
		if(lease != null && lease.isValid())
		{
			lease.renew();
			scheduler = registry.get(objectId);
		}
		return scheduler;
	}

	public ObjectScheduler removeLease(String objectId) 
	{
		ObjectScheduler scheduler = null;
		leaseMap.remove(objectId);
		scheduler = registry.remove(objectId);
		
		return scheduler;
	}
	
	public void shutdown() 
	{	
		registry.shutdown();
	}

	public boolean hasLease(String objectId) 
	{	
		boolean hasLease = false;
		Lease lease = leaseMap.get(objectId);
		hasLease = lease != null && lease.isValid() && registry.contains(objectId);
		return hasLease;
	}

	public List<String> getObjectIds() {
		List<String> ids = new ArrayList<String> ();
		synchronized(leaseMap)
		{
			for( String id : leaseMap.keySet())
			{
				ids.add(id);
			}
		}
		return ids;
	}

	public Lease getLease(String objectId) {
		return leaseMap.get(objectId);
		
	}

	

	
	

}
